import {
    BadRequestException,
    Body,
    Controller,
    Get,
    Header,
    HttpCode,
    Post,
    Query,
    Req,
    Res
} from '@nestjs/common';
import { createDecipheriv, createHash } from 'crypto';
import { query, Request, Response } from 'express';
import { AuthService } from 'src/auth/auth.service';
import { WechatService } from './wechat.service';
import { create } from 'xmlbuilder2';
import axios from 'axios';
import { UtilsService } from 'src/utils/utils.service';
/**
 * 微信回调给开发者的消息
 */
interface IWxMessageXmlData {
    /** 开发者微信号 e.g. `gh_019087f88815`*/
    ToUserName: string;
    /** 发送方帐号（一个OpenID）e.g.: `o5w5awUl***5pIJKY`*/
    FromUserName: string;
    /** 消息创建时间 （整型）e.g.`1595855711` */
    CreateTime: string;
    /** 消息类型，此处为 `event` */
    MsgType: string;
    /** 事件类型，subscribe(订阅)、unsubscribe(取消订阅) */
    Event: 'subscribe' | 'unsubscribe' | 'SCAN';
    /** 事件KEY值，目前无用 */
    EventKey: string;
}



@Controller('wechat')
export class WechatController {
    constructor(
        private readonly wechatService: WechatService,
        private readonly authService: AuthService,
        private readonly utilsService: UtilsService
    ) { }

    @Get('getOpenId')
    getOpenId(@Query() query) {
        return this.wechatService.getOpenId(query, this.authService);
    }


    @HttpCode(200)
    @Post('message')
    async messagePull(@Body('xml') body: IWxMessageXmlData, @Query() query: any, @Res() res: Response, @Req() req: Request) {
        console.log(body);
        const token = 'bangkeeducom2MessageToken';
        const { openid, signature, timestamp, nonce } = query;
        const tmpArr = [token, timestamp, nonce]
        tmpArr.sort();
        const tmpStr = createHash('sha1').update(tmpArr.join('')).digest('hex');
        if (tmpStr === signature) {
            if (body.MsgType == 'event') {
                if (body.Event == 'subscribe' || body.Event == 'SCAN') {
                    // 观看视频扫码
                    if (body.EventKey.includes('watchVideo')) {
                        res.send('success');
                        return;
                    }
                    if (this.wechatService.userTokenIsHas(body.EventKey)) {
                        res.send('success');
                        return;
                    }
                    const wx_access_token = this.wechatService.getAccessToken('wx_access_token');
                    const user = await this.authService.qrCodeLogin(openid, wx_access_token);
                    if (user) {
                        const fileName = body.EventKey.replace('qrscene_', '');
                        this.wechatService.setUserToken(fileName, JSON.stringify(user));
                        setTimeout(() => {
                            if (!this.wechatService.userTokenIsHas(body.EventKey)) {
                                return;
                            }
                            this.wechatService.removeUserToken(fileName);
                        }, 16000);
                        res.send('success');
                        return;
                    }
                }
            }

            // const EncodingAESKey = 'RNGHwzz7CuWebv2n6xoXZ27z1xtcugRjjOjSVKIhKm9'
            // const aesKey = Buffer.from(EncodingAESKey + '=', 'base64');
            // const cipher = createDecipheriv('aes-256-cbc', aesKey, aesKey.slice(0, 16))
            // cipher.setAutoPadding(false);
            res.send('success');
        }

    }

    @Get('message')
    getMessagePull(@Query() query: any) {
        console.log(query);
        const token = 'bangkeeducom2MessageToken';
        const { signature, timestamp, nonce, echostr } = query;
        const tmpArr = [token, timestamp, nonce]
        tmpArr.sort();
        const tmpStr = createHash('sha1').update(tmpArr.join('')).digest('hex');
        if (tmpStr === signature) {
            return echostr;
        }
        return false;
    }

    @Get('qrcode')
    qrcodeLogin(@Query() query: any) {
        if (!query.scene_str) {
            throw new BadRequestException()
        }
        return this.wechatService.qrCodeLogin(query.scene_str);
    }

    @Get('qrcode/token')
    qrcodeLoginToken(@Query() query: { scene_str: string }) {
        const userToken = this.wechatService.getUserToken(query.scene_str);
        if (userToken) {
            this.wechatService.removeUserToken(query.scene_str);
        }
        return userToken;
    }

    // 公众号内微信授权登录。
    @Post('public/auth')
    async publicAuth(@Body() body: { code: string }) {
        if (body.code) {
            try {
                const result = await this.wechatService.createUserAuthAccessToken(body.code);
                console.log(result);
                if (!result.errcode) {
                    return await this.authService.publicLogin(result.access_token, result.openid)
                }
            } catch (error) {
                console.log(error);
                return {
                    error: '',
                    message: ''
                }
            }
        }
    }


    @Post('public/menu/create')
    async publicMenuCreate(@Body() body) {
        const { data } = await axios.post('https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' + this.wechatService.getAccessToken('wx_access_token'), body);
        return data
    }

    // jssdk 签名
    @Get('public/jssdk/signature')
    async getPublicJSSDKSignature(@Query() query: { url: string }) {
        if (query.url) {
            // if (query.url === 'https://bangkeedu.com/from') {
            return this.wechatService.jsapiSignature(query.url, this.utilsService);
            // }
        }
    }

    @Get('bindPhone')
    async bindPhone(@Query() query: { avatarUrl: string, nickName: string, unionid: string, code: string }) {
        await this.wechatService.getWechatUserPhoneNumber(query);
    }
}